<template>
  <div class="singer">
    <cube-index-list :data="list">
      <cube-index-list-group
        v-for="(group, index) in list"
        :key="index"
        :group="group">
        <cube-index-list-item
          v-for="(item, index) in group.items"
          :key="index"
          :item="item">
          <div class="custom-item flex flex-vertical-center" @click="toSingerDetail(item)">
            <img :src="item.avatar" alt="" class='kaho-img'>
            <span class="kaho-name">{{item.name}}</span>
          </div>
        </cube-index-list-item>
      </cube-index-list-group>
    </cube-index-list>
    <router-view></router-view>
  </div>
</template>
<script>
import {getSingerList} from '@/api/singer'
import {ERR_OK} from '@/api/config'
import axios from 'axios'
import Singer from '@/common/singer'
import {mapMutations, mapState} from 'vuex' //注册 mutation 和 state

const HOT_SINGER_LEN = 10
const HOT_NAME = '热门'

export default {
  name: 'singer',

  data(){
    return {
      list: []
    }
  },

  methods: {
    _getSingerList() {
      getSingerList().then((res) => {
        if (res.code === ERR_OK) {
          this.list = this._normalizeSinger(res.data.list);
        }
      })
    },

    _normalizeSinger(list){
      let map = {
        hot: {
          name: HOT_NAME,
          items: []
        }
      }

      list.forEach((element, index) => {
        if(index < HOT_SINGER_LEN){
          map.hot.items.push(new Singer({
            name: element.Fsinger_name,
            id: element.Fsinger_mid
          }))
        } 
        
        const key = element.Findex

        if(!map[key]){
          map[key] = {
            name: key,
            items: []
          }
        }

        map[key].items.push(new Singer({
          name: element.Fsinger_name,
          id: element.Fsinger_mid
        }))

      });

      // 为了得到有序列表，我们需要处理 map
      let ret = []
      let hot = []
      for (let key in map) {
        let val = map[key]
        if (val.name.match(/[a-zA-Z]/)) {
          ret.push(val)
        } else if (val.name === HOT_NAME) {
          hot.push(val)
        }
      }
      ret.sort((a, b) => {
        return a.name.charCodeAt(0) - b.name.charCodeAt(0)
      })
      return hot.concat(ret)
    },

    toSingerDetail(item) {
      // console.log(this.$router)
      this.$router.push({
        path: `/singer/${item.id}`
      })
      this.setSinger(item)
    },

    ...mapMutations([
        'setSinger'
    ]),

  },

  created(){
    this._getSingerList();
  }
}
</script>
<style scoped lang="stylus">
.singer{
  position: fixed;
  top: 88px;
  bottom: 0;
  width: 100%;
}

.custom-item{
  padding: 15px 30px;

  .kaho-img{
    width: 50px;
    height: 50px;
    border-radius: 50%;
  }

  .kaho-name{
    margin-left: 20px;
    color: hsla(0,0%,100%,.5);
    font-size: 14px;
  }
}
</style>
